package com.lmc.me;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.lmc.R;
import com.lmc.adapter.FeedbackImgAdapter;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.robot.PermissionHelper;
import com.qxzn.app.page.util.GlideImageLoader;
import com.qxzn.app.util.CommonUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.SharePreferenceUtil;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 意见反馈
 */
public class FeedbackActivity extends BaseActivity implements TextWatcher, FeedbackImgAdapter.OnClick {

    private EditText et_content;
    private TextView tv_content_num;
    private TextView tv_img_num;
    private RecyclerView img_recyclerView;
    private EditText et_phone;
    private TextView post;
    private FeedbackImgAdapter adapter;
    private List<String> img_list = new ArrayList<>();

    @Override
    protected int initLayout() {
        return R.layout.activity_feedback;
    }

    @Override
    protected void initView() {

        et_content = (EditText) findViewById(R.id.et_content);
        tv_content_num = (TextView) findViewById(R.id.tv_content_num);
        tv_img_num = (TextView) findViewById(R.id.tv_img_num);
        img_recyclerView = (RecyclerView) findViewById(R.id.img_recyclerView);
        et_phone = (EditText) findViewById(R.id.et_phone);
        post = (TextView) findViewById(R.id.post);
        post.setOnClickListener(this);
    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText("意见反馈");
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

        img_list.add("");
        adapter = new FeedbackImgAdapter(this, img_list, this);
        img_recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        img_recyclerView.setAdapter(adapter);

        et_content.addTextChangedListener(this);

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.post) {
            Post();
        }
    }

    private void Post() {
        // validate
        JSONObject params = new JSONObject();
        String content = et_content.getText().toString().trim();
        if (TextUtils.isEmpty(content) || content.length() < 10) {
            Toast.makeText(this, "请填写10个字以上的问题描述，以便我们提供更好的帮助", Toast.LENGTH_SHORT).show();
            return;
        }

        String phone = et_phone.getText().toString().trim();
        if (!TextUtils.isEmpty(phone)) {
            if (!CommonUtil.isMobile(phone)) {
                Toast.makeText(this, "不是正确的手机号码", Toast.LENGTH_SHORT).show();
                return;
            }
            params.put("phone", phone);
        }

        params.put("username", SharePreferenceUtil.getUserName(this));
        params.put("device_id", SharePreferenceUtil.getDeviceId(this));
        params.put("content", content);
        params.put("type", "1");

        HttpRequest.getService().addFeedback(HttpRequest.getDefaultBody(params)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Log.e("-----------", "提交意见反馈：" + string);
                    Toast.makeText(mActivity, "提交成功", Toast.LENGTH_LONG).show();
                    finish();
                } catch (Exception e) {
                    Log.e("-----", e.toString());
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });


    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        tv_content_num.setText(et_content.getText().toString().length() + "/200");
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 添加图片
     */
    @Override
    public void add() {
        PermissionHelper.checkCameraPermission(this, new PermissionHelper.OnDoneListener() {
            @Override
            public void onDone() {
                getPicture(5 - img_list.size(), 1);
            }
        });
    }

    private void getPicture(int maxSelectable, int requestCode) {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .capture(true)
                .maxSelectable(maxSelectable)
                .captureStrategy(new CaptureStrategy(true, Constant.authority))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideImageLoader.Glide4Engine())
                .forResult(requestCode);
    }

    /**
     * 删除图片
     *
     * @param i
     */
    @Override
    public void del(int i) {
        img_list.remove(i);
        setImgList();
    }

    private void setImgList() {
        for (int j = 0; j < img_list.size(); j++) {
            if (TextUtils.isEmpty(img_list.get(j))) {
                img_list.remove(j);
            }
        }

        tv_img_num.setText(img_list.size() + "/4");
        if (img_list.size() < 4) {
            img_list.add("");
        }
        adapter.notifyDataSetChanged();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1) {
            List<String> mSelected = Matisse.obtainPathResult(data);
            if (mSelected != null && mSelected.size() > 0) {
                Log.e("----------", "图片路径：" + mSelected.get(0));
                img_list.addAll(mSelected);
                setImgList();
            }
        }
    }

}
